package cn.zyjblogs.netty.groupchat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * 客户端
 */
public class GroupChatClient {

    /**
     * 主机ip
     */
    private final String HOST;
    /**
     * 主机端口
     */
    private final Integer PORT ;

    public GroupChatClient(String host,Integer port) {
        this.HOST = host;
        this.PORT = port;
    }
    public void run() {
        EventLoopGroup eventExecutors = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventExecutors)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        //得到pipeline
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast("decoder",new StringDecoder())
                                .addLast("encoder",new StringEncoder())
                                .addLast(new GroupChatClientHandler());
                    }
                });
        try {
            ChannelFuture sync = bootstrap.connect(HOST, PORT).sync();
            Channel channel = sync.channel();
            System.out.println("----------"+channel.localAddress()+"---------");
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()){
                String s = scanner.nextLine();
                channel.writeAndFlush(s+"\r\n");
            }
            sync.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            eventExecutors.shutdownGracefully();
            System.out.println("客户端关闭");
        }
    }
    public static void main(String[] args) {
        new GroupChatClient("127.0.0.1",7000).run();;
    }
}
